program define dh_export

	syntax using/, [id(varlist) Digits(int 3)]
	
	if strpos("`using'",".csv")==0 {
		noi di as error "Must export as .csv file."
		exit 198
	}
	
	* Sort and check ID
	order `id'
	sort `id'
	isid `id'
	
	* Reduce data precision to 3 sig figs
	qui ds `id', not
	sigdig `r(varlist)', digits(`digits') afterdecimal replace
	
	* Export
	export delimited "`using'", replace
	project, creates("`using'") preserve
	
end

program define sigdig

	syntax varlist(numeric), Digits(int) [GENerate(name) REPlace afterdecimal]

	if "`generate'" == "" & "`replace'" == "" {
		noi di as error "Must specify one of generate or replace."
		exit 198
	}
	
	if "`generate'" != "" & "`replace'" != "" {
		noi di as error "Cannot specify both generate and replace"
		exit 198
	}
	
	foreach var of local varlist {
			
		tempvar scale temp
		
		* Move all significant digits to the right hand side (234.4 --> 0.2344)
		gen `scale' = 10^(floor(log10(abs(`var'))+1)) if `var' != 0
		
		* Now we round
		local precision = 10^(-`digits') // Stata's round command is weird so if we want 5 digits we specify 0.00001
	
		if ("`afterdecimal'"=="") gen double `temp' = round(`var'/`scale', `precision') * `scale'
		else gen double `temp' = cond(`var'<1000, round(`var'/`scale', `precision') * `scale', `var')
		
		* Deal with zero
		qui replace `temp' = 0 if `var' == 0
		
		format `temp' %12.9f
		
		* Output
		if "`generate'" != "" {
			gen `generate' = string(`temp', "%16.`digits'g")
		}
		
		if "`replace'" != "" {
			rename `var' `var'_old
			gen `var' = string(`temp', "%16.`digits'g")
			drop `var'_old
		}
		
		drop `scale' `temp'
	}
	
end
